<%--
  Created by IntelliJ IDEA.
  User: lin
  Date: 2019/1/3
  Time: 16:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>江苏大学学生信息管理系统</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <script type="text/javascript"
            src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
    <link
            href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
            rel="stylesheet"/>
    <script
            src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

<!--确认批量删除模态框-->
<div class="modal fade bs-example-modal-sm" id="confirmDeleteAllModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <div align="center">
                    <h2 class="modal-title" >
                        <font color="#FF0000"><strong>删除提醒</strong></font>
                    </h2>
                </div>
            </div>
            <div class="modal-body">
                <div align="center" id="confirm_delete_all_div">
                    <h4>
                        你是否要删除
                    </h4>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-warning" id="confirm_delete_all_btn">确认</button>
                <button type="button" class="btn btn-info" data-dismiss="modal">取消</button>

            </div>
        </div>
    </div>
</div>


<!--确认删除模态框-->
<div class="modal fade bs-example-modal-sm" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <div align="center">
                <h2 class="modal-title" >
                    <font color="#FF0000"><strong>删除提醒</strong></font>
                </h2>
                    </div>
            </div>
            <div class="modal-body">
                <div align="center" id="confirm_delete_div">
                    <h4>
                        你是否要删除
                    </h4>
                </div>
            </div>
            <div class="modal-footer">
                        <button type="button" class="btn btn-warning" id="confirm_delete_btn">确认</button>
                        <button type="button" class="btn btn-info" data-dismiss="modal">取消</button>
            </div>
            </div>
        </div>
    </div>
</div>


<!-- 添加学生模态框-->
<div class="modal fade" id="stuAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">学生添加</h4>
            </div>
            <div class="modal-body">

                <form class="form-horizontal">-
                    <div class="form-group">
                        <label class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="stuName" placeholder="name" id="name_add_input">
                            <span class="help-block"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">籍贯</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="stuNativepalce" placeholder="NativePlace">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-8">
                        <label class="radio-inline">
                            <input type="radio" name="stuGender" value="M" checked="checked"> 男
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="stuGender" value="F"> 女
                        </label>
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label">学院</label>
                        <div class="col-sm-4">
                        <select class="form-control" name="iId" id="institute_add_select">


                        </select>
                        </div>

                    </div>

                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="stu_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>


<!-- 学生修改模态框-->
<div class="modal fade" id="stuUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" >学生修改</h4>
            </div>
            <div class="modal-body">

                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="stuName" placeholder="name" id="name_update_input">
                            <span class="help-block"></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">籍贯</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="stuNativepalce" placeholder="NativePlace" id="nativepalce_update_input">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-8">
                            <label class="radio-inline">
                                <input type="radio" name="stuGender" value="M" checked="checked" id="gender1_update_input"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="stuGender" value="F" id="gender2_update_input"> 女
                            </label>
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label">学院</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="iId" id="institute_update_select">


                            </select>
                        </div>

                    </div>

                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="stu_update_btn">修改</button>
            </div>
        </div>
    </div>
</div>


<!-- 页面基本构建-->
<div class="container">

    <!-- 标题-->
    <div class="row">
        <div class="col-md-12">
            <h1 align="center">学生信息管理</h1>
        </div>
    </div>
    <!--按钮-->
    <div class="row">
        <div class="col-md-1">
            <h4 align="center">欢迎您</h4>
        </div>
        <div class="col-md-5 col-md-offset-8">
            <button class="btn btn-primary" id="stu_add_modal_btn">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                新增
            </button>
            <button class="btn btn-danger" id="stu_delete_modal_btn">
                <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                删除
            </button>
        </div>
    </div>

    <!--显示表格-->
    <div class="row">

        <div class="col-md-12">

            <table class="table table-hover" id="stu_table">
                <thead>
                <tr>
                    <th><input type="checkbox" id="check_all"/></th>
                    <th>学&nbsp&nbsp号</th>
                    <th>姓&nbsp&nbsp名</th>
                    <th>性&nbsp&nbsp别</th>
                    <th>籍&nbsp&nbsp贯</th>
                    <th>学&nbsp&nbsp院</th>
                    <th>操&nbsp&nbsp作</th>
                </tr>
                </thead>

                <tbody>

                </tbody>


            </table>

        </div>

    </div>

    <!--分页条-->
    <div class="row">
        <!--分页文字信息  -->
        <div class="col-md-6" id="page_info_area"></div>
        <!-- 分页条信息 -->
        <div class="col-md-6" id="page_nav_area">

        </div>
    </div>

</div>


<!--实现Ajax动态页面-->
<script type="text/javascript">
    //记录总记录数和当前页面数
    var totalRecord,currentPage;

    //学生ID
    var stuId;

    //需要删除的学生ID集
    var del_idstr;


    //1、页面加载完成以后，直接去发送ajax请求,要到分页数据
    $(function(){
        //页面加载完成以后去首页
        to_page(1);
    });


    //调到第几页
    function to_page(pn){
        //发送Ajax请求获取当前页的分页数据
        $.ajax({
            url:"${APP_PATH}/stus",
            data:"pn="+pn,
            type:"GET",
            success:function(result){
                //console.log(result);
                //1、解析并显示学生数据
                build_student_table(result);
                //2、解析并显示分页信息
                build_page_info(result);
                //3、解析显示分页条数据
                build_page_nav(result);
            }
        });
    }


    <!--动态构建学生列表-->
    function build_student_table(result) {
        //显示之前先清空原来的表单数据
        $("#stu_table tbody").empty();
        //获取Json形式的学生数据
        var student=result.extend.pageInfo.list;
        $.each(student,function (index, item) {
            //创建第一列的选中框
            var checkBoxTd=$("<td><input type='checkbox' class='check_item'/></td>");
            //学生ID
            var stuIdTd=$("<td></td>").append(item.stuId);
            //学生姓名
            var stuNameTd=$("<td></td>").append(item.stuName);
            //学生性别
            var stuGenderTd=$("<td></td>").append(item.stuGender=='M'?"男":"女");
            //学生籍贯
            var stuNativepalceTd=$("<td></td>").append(item.stuNativepalce);
            //学生学院的ID
            var iIdTd=$("<td></td>").append(item.institute.instituteName);
            //创建编辑按钮 并附加class属性edit_btn
            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
            //为编辑按钮添加一个自定义的属性，来表示当前学生id
            editBtn.attr("edit-id",item.stuId);
            //创建删除按钮并增加class属性delete_btn
            var delBtn =  $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
            //为删除按钮添加一个自定义属性，来表是当前删除学生ID
            delBtn.attr("del-id",item.stuId);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);
            //添加到<tr></tr>
            $("<tr></tr>").append(checkBoxTd)
                .append(stuIdTd)
                .append(stuNameTd)
                .append(stuGenderTd)
                .append(stuNativepalceTd)
                .append(iIdTd)
                .append(btnTd)
                .appendTo("#stu_table tbody");
                //添加到表单的tbody标签中
        });
    }


    //解析显示分页信息
    function build_page_info(result){
        //清空先前的分页信息
        $("#page_info_area").empty();
        $("#page_info_area").append("当前"+result.extend.pageInfo.pageNum+"页,总"+
            result.extend.pageInfo.pages+"页,总"+
            result.extend.pageInfo.total+"条记录");
        totalRecord = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
    }


    //解析显示分页条，点击分页要能去下一页
    function build_page_nav(result){
        //page_nav_area
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");

        //构建元素
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
        if(result.extend.pageInfo.hasPreviousPage == false){
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        }else{
            //为元素添加点击翻页的事件
            firstPageLi.click(function(){
                to_page(1);
            });
            prePageLi.click(function(){
                to_page(result.extend.pageInfo.pageNum -1);
            });
        }



        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
        if(result.extend.pageInfo.hasNextPage == false){
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        }else{
            nextPageLi.click(function(){
                to_page(result.extend.pageInfo.pageNum +1);
            });
            lastPageLi.click(function(){
                to_page(result.extend.pageInfo.pages);
            });
        }



        //添加首页和前一页 的提示
        ul.append(firstPageLi).append(prePageLi);
        //1,2，3遍历给ul中添加页码提示
        $.each(result.extend.pageInfo.navigatepageNums,function(index,item){

            var numLi = $("<li></li>").append($("<a></a>").append(item));
            if(result.extend.pageInfo.pageNum == item){
                numLi.addClass("active");
            }
            numLi.click(function(){
                to_page(item);
            });
            ul.append(numLi);
        });
        //添加下一页和末页 的提示
        ul.append(nextPageLi).append(lastPageLi);

        //把ul加入到nav
        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area");
    }


    <!--新增按钮触发新增模态框-->
    $("#stu_add_modal_btn").click(function () {
        //清除表单数据
        reset_form("#stuAddModal form");
        //发送Ajax请求获取学院数据
        getInstitutes("#institute_add_select");
        //打开模态框
        $("#stuAddModal").modal({
            backdrop:"static"
        });
    });


    //发送Ajax请求获取学院信息
    function getInstitutes(ele) {
        $(ele).empty();
        $.ajax({
            url:"${APP_PATH}/institutes",
            type:"GET",
            success:function (result) {
                //显示学院信息在下拉列表中
                $.each(result.extend.institutes,function(){
                    var optionEle = $("<option></option>").append(this.instituteName).attr("value",this.instituteId);
                    optionEle.appendTo(ele);
                });
            }
        });
    }


    //学生添加时保存按钮触发
    $("#stu_save_btn").click(function () {
        //先对要提交给服务器的数据进行校验

        if(!validate_add_form()){
            return false;
        };

        //判断之前的ajax姓名校验是否成功

        if($(this).attr("ajax-va")=="error"){
            return false;
        }

        //如果成功发送ajax请求保存数据
        $.ajax({
            url:"${APP_PATH}/stu",
            type:"POST",
            //序列化
            data:$("#stuAddModal form").serialize(),
            success:function (result) {
                //判断Json数据中的处理Code是否为成功
                if (result.code == 100) {
                    $("#stuAddModal").modal("hide");
                    //跳转到最后一页显示当前添加的学生信息，这里用总记录数代表最后一页
                    to_page(totalRecord);
                }else{
                    //显示学生名字的错误信息
                    if(undefined != result.extend.errorFields.stuName){
                        show_validate_msg("#name_add_input", "error", result.extend.errorFields.stuName);
                    }
                }
            }
        })
    })


    //校验表单数据
    function validate_add_form(){
        //1、拿到要校验的数据
        var stuName = $("#name_add_input").val();
        //使用正贼表达式
        var regName = /(^[\u2E80-\u9FFF]{2,4})/;
        //判断是否符合正则表达式，不符合则输出提示信息
        if(!regName.test(stuName)){
            show_validate_msg("#name_add_input", "error", "姓名只能是2-4位中文");
            return false;
        }else{
            //成功则使输入框变绿
            show_validate_msg("#name_add_input", "success", "");
        };
        return true;
    }


    //显示校验结果的提示信息
    function show_validate_msg(ele,status,msg){
        //清除当前元素的校验状态
        $(ele).parent().removeClass("has-success has-error");
        $(ele).next("span").text("");
        if("success"==status){
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        }else if("error" == status){
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    }


    //清空表单样式及内容
    function reset_form(ele){
        $(ele)[0].reset();
        //清空表单样式
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }


    //校验用户名是否可用
    $("#name_add_input").change(function(){
        //发送ajax请求校验用户名是否可用
        var stuName = this.value;
        //发送Ajax请求,Controller层也要进行正则表达式校验
        $.ajax({
            url:"${APP_PATH}/checkUser",
            data:"stuName="+stuName,
            type:"POST",
            success:function(result){
                if(result.code==100){
                    show_validate_msg("#name_add_input","success","用户名可用");
                    $("#stu_save_btn").attr("ajax-va","success");
                }else{
                    show_validate_msg("#name_add_input","error",result.extend.va_msg);
                    $("#stu_save_btn").attr("ajax-va","error");
                }
            }
        });
    });


    //按钮创建之前就绑定了click,所以直接使用click绑定不上。
    // 使用on进行替代
    $(document).on("click",".edit_btn",function(){
        //清空更新模态框表单数据
        reset_form("#stuUpdateModal form");
        //1、查出学院信息，并显示学院列表
        getInstitutes("#stuUpdateModal select");
        //2、查出学生信息，显示该学生信息
        getStu($(this).attr("edit-id"));
        //3、把学生的id传递给模态框的更新按钮
        $("#stu_update_btn").attr("edit-id",$(this).attr("edit-id"));
        $("#stuUpdateModal").modal({
            backdrop:"static"
        });
    });


    //通过学生id回显学生数据
    function getStu(id){
        $.ajax({
            url:"${APP_PATH}/stu/"+id,
            type:"GET",
            success:function(result){
                //console.log(result);
                var stuData = result.extend.student;
                $("#name_update_input").val(stuData.stuName);
                $("#nativepalce_update_input").val(stuData.stuNativepalce);
                $("#stuUpdateModal input[name=stuGender]").val([stuData.stuGender]);
                $("#institute_update_select").val([stuData.iId]);
            }
        });
    }


    //点击更新，更新学生信息
    $("#stu_update_btn").click(function(){
        //验证更新的姓名是否合法
        var stuName = $("#name_update_input").val();
        var regName = /(^[\u2E80-\u9FFF]{2,4})/;
        if(!regName.test(stuName)){
            show_validate_msg("#name_update_input", "error", "姓名只能是2-4位中文");
            return false;
        }else{
            show_validate_msg("#name_update_input", "success", "");
        }
        //2、发送ajax请求保存更新的学生数据
        $.ajax({
            url:"${APP_PATH}/stu/"+$(this).attr("edit-id"),
            //发送put请求实现restful风格，但必须在web.xml中加入过滤器
            type:"PUT",
            data:$("#stuUpdateModal form").serialize(),
            success:function(result){
                //隐藏更新模态框
                $("#stuUpdateModal").modal("hide");
                //2、回到本页面
                to_page(currentPage);
            }
        });
    });


    //校验姓名是否可用
    $("#name_update_input").change(function(){
        //发送ajax请求校验姓名是否可用
        var stuName = this.value;
        $.ajax({
            url:"${APP_PATH}/checkUser",
            data:"stuName="+stuName,
            type:"POST",
            success:function(result){
                if(result.code==100){
                    show_validate_msg("#name_update_input","success","用户名可用");
                    $("#stu_update_btn").attr("ajax-va","success");
                }else{
                    show_validate_msg("#name_update_input","error",result.extend.va_msg);
                    $("#stu_update_btn").attr("ajax-va","error");
                }
            }
        });
    });


    //完成全选/全不选功能
    $("#check_all").click(function(){
        //attr获取checked是undefined;
        //attr获取自定义属性的值；
        //prop修改和读取dom原生属性的值
        //checked是原生属性的值
        $(".check_item").prop("checked",$(this).prop("checked"));
    });


    //check_item
    $(document).on("click",".check_item",function(){
        //判断当前选择中的元素是否5个，五个则全选按钮也要选中
        var flag = $(".check_item:checked").length==$(".check_item").length;
        $("#check_all").prop("checked",flag);
    });


    //单个删除
    $(document).on("click",".delete_btn",function(){
        //获取删除按钮添加的学生ID
        stuId = $(this).attr("del-id");
        //1、弹出是否确认删除对话框
        $("#confirmDeleteModal").modal({
            backdrop:"static"
        });
    });


    //确认删除按钮
    $("#confirm_delete_btn").click(function () {
        //如果确认，发送ajax请求删除
        $.ajax({
            url:"${APP_PATH}/stu/"+stuId,
            //DELETE请求,实现restful风格
            type:"DELETE",
            success:function(result){
                //关闭确认删除模态框
                $("#confirmDeleteModal").modal("hide");
                //回到本页
                to_page(currentPage);
            }
        });
    })


    //点击全部删除，就批量删除
    $("#stu_delete_modal_btn").click(function(){
        del_idstr = "";
        $.each($(".check_item:checked"),function(){
            //组装学生id字符串,之间加上-
            del_idstr += $(this).parents("tr").find("td:eq(1)").text()+"-";
        });
        //去除删除的id多余的-
        del_idstr = del_idstr.substring(0, del_idstr.length-1);
        $("#confirmDeleteAllModal").modal({
            backdrop:"static"
        });
    });


    //出发批量删除按钮
    $("#confirm_delete_all_btn").click(function () {
        //确认，发送ajax请求删除即可
        $.ajax({
            //发送的是删除的学生ID的“集合”
            url:"${APP_PATH}/stu/"+del_idstr,
            type:"DELETE",
            success:function(result){
                //关闭批量删除的模态框
                $("#confirmDeleteAllModal").modal("hide");
                //回到本页
                to_page(currentPage);
            }
        });
    })

</script>

</body>
</html>
